package cc.catface.smsdemo;

import cc.catface.smsdemo.sendmsg.NumberUtil;
import cc.catface.smsdemo.sendmsg.SmsUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 云MAS平台短信服务
 */
@RestController
@RequestMapping(value = "check")
public class SmsController {

    protected static final Logger logger = LoggerFactory.getLogger(SmsController.class);

    @Autowired
    private SmsServiceImpl smsService;

    /**
     * @description
     *      1、调用云MAS发送短信，成功将手机号、验证码、时间戳插入或更新至数据库并返回成功，发送失败返回失败
     * @param phoneid   手机号
     */
    @GetMapping("getscode")
    public Boolean getscode(@RequestParam(name = "phoneid", required = true) String phoneid) {
        String code = NumberUtil.getRandom(4);
        logger.debug("send msg, phoneid:" + phoneid + ", code:" + code);
        Boolean success = SmsUtils.sendMsg(phoneid, code);
        success = true;
        if (!success) return false;//短信发送失败
        smsService.saveCode(phoneid, code);
        return true;
    }

    /**
     * @description
     *      1、查表，校验phoneid、code、当前时间与表中最近发送短信timestamp是否在2分钟内
     *      2、全部匹配返回true，否则返回false
     * @param phoneid   手机号
     * @param code      验证码
     */
    @GetMapping("checkscode")
    public String checkscode(String phoneid, String code) {
        return smsService.checkscode(phoneid, code);
    }
}
